using IMServer.Models;
using MongoDB.Driver;
using IMServer.Database;

namespace IMServer.Services
{
    public class GroupDbService
    {
        private static readonly GroupDbService _instance = new GroupDbService();
        private static IMongoCollection<Group>? _groupsCollection;

        private GroupDbService()
        {
            try
            {
                Console.WriteLine("Starting GroupDbService initialization...");
                var dbContext = MongoDBContext.Instance;
                _groupsCollection = dbContext.Groups;

                if (_groupsCollection == null)
                    throw new InvalidOperationException("Failed to initialize groups collection");

                // 创建索引
                var indexOptions = new CreateIndexOptions { Unique = true };
                var indexKeys = Builders<Group>.IndexKeys.Ascending(x => x.GroupId);
                _ = _groupsCollection.Indexes.CreateOne(new CreateIndexModel<Group>(indexKeys, indexOptions));

                Console.WriteLine("GroupDbService initialized successfully");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error initializing GroupDbService: {ex.Message}");
                throw;
            }
        }

        public static GroupDbService Instance => _instance;

        // 创建新群组
        public async Task<Group> CreateGroupAsync(Group group)
        {
            if (_groupsCollection == null)
                throw new InvalidOperationException("Database not initialized");

            await _groupsCollection.InsertOneAsync(group);
            return group;
        }

        // 根据群组ID获取群组
        public async Task<Group> GetGroupByIdAsync(string groupId)
        {
            return await _groupsCollection.Find(x => x.GroupId == groupId).FirstOrDefaultAsync();
        }

        // 添加群组成员
        public async Task<bool> AddMemberAsync(string groupId, string userId)
        {
            if (_groupsCollection == null)
                throw new InvalidOperationException("Database not initialized");

            var update = Builders<Group>.Update.AddToSet(x => x.Members, userId);
            var result = await _groupsCollection.UpdateOneAsync(
                x => x.GroupId == groupId,
                update);

            return result.ModifiedCount > 0;
        }
        
        // 移除群组成员
        public async Task<bool> RemoveMemberAsync(string groupId, string userId)
        {
            if (_groupsCollection == null)
                throw new InvalidOperationException("Database not initialized");

            var update = Builders<Group>.Update.Pull(x => x.Members, userId);
            var result = await _groupsCollection.UpdateOneAsync(
                x => x.GroupId == groupId,
                update);

            return result.ModifiedCount > 0;
        }

        // 更新群组信息
        public async Task<bool> UpdateGroupAsync(string groupId, string? groupName = null, string? avatar = null)
        {
            if (_groupsCollection == null)
                throw new InvalidOperationException("Database not initialized");

            UpdateDefinition<Group> update; 
            if (groupName != null && avatar != null)
            {
                update = Builders<Group>.Update
                    .Set(x => x.GroupName, groupName)
                    .Set(x => x.Avatar, avatar);
            }else if (groupName != null)
            {
                update = Builders<Group>.Update
                    .Set(x => x.GroupName, groupName);
            }else if (avatar != null)
            {
                update = Builders<Group>.Update
                    .Set(x => x.Avatar, avatar);
            }else
            {
                return false;
            }

            var result = await _groupsCollection.UpdateOneAsync(
                x => x.GroupId == groupId,
                update);

            return result.ModifiedCount > 0;
        }

        public async Task<IEnumerable<Group>> GetGroupsByIdsAsync(IEnumerable<string> groupIds)
        {
            if (_groupsCollection == null)
                throw new InvalidOperationException("Database not initialized");
            
            var filter = Builders<Group>.Filter.In(x => x.GroupId, groupIds);
            return await _groupsCollection.Find(filter).ToListAsync();
        }
    }
}
